<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Configuration
 *
 * @author MinhNguyen
 */
class User {

    //put your code here
    public $id;
    public $name;
    public $password;
    public $email;
    public $phone;
    public $address;
    public $company;
    public $position;
    public $timezone;
    public $dateRegistered;
    public $token;
    public $managerId;
    public $teamId;
    public $type;
    public static $instance;

    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __get($name) {
        return $this->$name;
    }

    public function __set($name, $value) {
        $this->$name = $value;
    }

    /**
     * It's constuctor of User with email
     */
    public function __construct() {
        //allocate your stuff
    }

    /**
     * Print message if email is not found in database
     * or print error message if can not connect database
     */
    public static function withEmail($email) {
        $instance = new self();
        $db = Database::getInstance();
        $query = "SELECT * FROM users WHERE email = '$email'";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $rows = $result->dataTable->rows[0];
                $instance->id = $rows["id"];
                $instance->name = $rows["fullname"];
                $instance->password = $rows["password"];
                $instance->email = $rows["email"];
                $instance->phone = $rows["phone"];
                $instance->address = $rows["address"];
                $instance->company = $rows["company"];
                $instance->position = $rows["position"];
                $instance->timezone = $rows["timezone"];
                $instance->dateRegistered = $rows["dateregistered"];
                $instance->token = $rows["token"];
                $instance->teamId = $rows["teamid"];
                $instance->type = $rows["type"];
                return $instance;
            } else {
                $controller = new ErrorController(new Error(), new ErrorView(), "404", "Not found any user with provided email");
                $controller->returnError();
                return NULL;
            }
        } else {
            $controller = new ErrorController(new Error(), new ErrorView, $result->returnCode, $result->message);
            $controller->returnError();
            return NULL;
        }
    }

    public static function withData($nameUser, $password, $email) {
        $instance = new self();
        $instance->nameUser = $nameUser;
        $instance->password = $password;
        $instance->email = $email;
        return $instance;
    }

    public static function withId($id) {
        $instance = new self();
        $db = Database::getInstance();
        $query = "SELECT * FROM users WHERE userid = '$id'";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $rows = $result->dataTable->rows[0];
                $instance->id = $rows["userid"];
                $instance->name = $rows["fullname"];
                $instance->password = $rows["password"];
                $instance->email = $rows["email"];
                $instance->phone = $rows["phone"];
                $instance->address = $rows["address"];
                $instance->company = $rows["company"];
                $instance->position = $rows["position"];
                $instance->dateRegistered = $rows["dateregistered"];
                $instance->token = $rows["token"];
                $instance->timezone = $rows["timezone"];
                $instance->managerId = $rows["managerid"];
                $instance->teamId = $rows["teamid"];
                $instance->type = $rows["type"];
                return $instance;
            } else {
                $controller = new ErrorController(new Error(), new ErrorView(), "404", "Not found any user with provided email");
                $controller->returnError();
                return NULL;
            }
        } else {
            $controller = new ErrorController(new Error(), new ErrorView, $result->returnCode, $result->message);
            $controller->returnError();
            return NULL;
        }
    }

    public static function getFolder() {
        if (self::getCurrentUserId()) {
            $db = Database::getInstance();
            $userId = self::getCurrentUserId();
            $user = User::withId($userId);
            $query = "SELECT * FROM folders WHERE userid IN (SELECT userid FROM users WHERE teamid = (SELECT teamid FROM users WHERE userid = $userId)) ORDER BY folderid";
            //$query = "SELECT * FROM folders LEFT JOIN foldershare ON folders.folderid = foldershare.folderid WHERE foldershare.sharewith = '$user->teamId' ORDER BY folders.folderid";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    foreach ($result->dataTable->rows as $row) {
                        $id = $row['folderid'];
                        $name = $row['foldername'];
                        $parentid = $row["parentid"];
                        $folderId = "$folderId$id;";
                        $foldername = "$foldername$name;";
                        $parentId = "$parentId$parentid;";
                    }
                    return array(
                        'folderid' => $folderId,
                        'foldername' => $foldername,
                        'parentid' => $parentId
                    );
                } else {
                    /* $controller = new ErrorController(new Error(), new ErrorView(), 
                      "404", "Not found any user with provided email");
                      $controller->returnError(); */
                    return array(
                        'folderid' => 'undefined',
                        'foldername' => 'undefined',
                        'parentid' => 'undefined'
                    );
                }
            } else {
                /* $controller = new ErrorController(new Error(), new ErrorView, 
                  $result->returnCode, $result->message);
                  $controller->returnError(); */
                return array(
                    'folderid' => 'undefined',
                    'foldername' => 'undefined',
                    'parentid' => 'undefined'
                );
            }
        } else {
            return array(
                'folderid' => 'undefined',
                'foldername' => 'undefined',
                'parentid' => 'undefined'
            );
        }
    }

    public static function getUser() {
        if (User::getCurrentUserId()) {
            $db = Database::getInstance();
            $userId = User::getCurrentUserId();
            $query = "SELECT * FROM users WHERE managerid = '$userId'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    foreach ($result->dataTable->rows as $row) {
                        $id = $row['userid'];
                        $name = $row['fullname'];
                        $mail = $row['email'];
                        $md5 = md5($mail);
                        $lastlogin = User::withId($id)->getLastLogin();
                        $userid = "$userid$id;";
                        $username = "$username$name;";
                        $usermail = "$usermail$mail;";
                        $avatar = "$avatar$md5;";
                        $userlogin = "$userlogin$lastlogin;";
                    }
                    return array(
                        'userid' => $userid,
                        'username' => $username,
                        'usermail' => $usermail,
                        'lastlogin' => $userlogin,
                        'avatar' => $avatar
                    );
                } else {
                    /* $controller = new ErrorController(new Error(), new ErrorView(), 
                      "404", "Not found any user with provided email"); */
                    return array(
                        'userid' => 'undefined',
                        'username' => 'undefined',
                        'usermail' => 'undefined',
                        'lastlogin' => 'undefined'
                    );
                }
            } else {
                /* $controller = new ErrorController(new Error(), new ErrorView, 
                  $result->returnCode, $result->message);
                  $controller->returnError(); */
                return array(
                    'userid' => 'undefined',
                    'username' => 'undefined',
                    'usermail' => 'undefined',
                    'lastlogin' => 'undefined'
                );
            }
        } else {
            return array(
                'userid' => 'undefined',
                'username' => 'undefined',
                'usermail' => 'undefined',
                'lastlogin' => 'undefined'
            );
        }
    }

    public static function getTag() {
        if (User::getCurrentUserId()) {
            $db = Database::getInstance();
            $user = User::getLogedInUser();
            $query = "SELECT * FROM tags WHERE userid IN (SELECT userid FROM users WHERE teamid = $user->teamId) OR userid = '0'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    foreach ($result->dataTable->rows as $row) {
                        $id = $row['tagid'];
                        $name = $row['tagname'];
                        $tagid = "$tagid$id;";
                        $tagname = "$tagname$name;";
                    }
                    return array(
                        'tagid' => $tagid,
                        'tagname' => $tagname
                    );
                } else {
                    /* $controller = new ErrorController(new Error(), new ErrorView(), 
                      "404", "Not found any user with provided email"); */
                    return array(
                        'tagid' => 'undefined',
                        'tagname' => 'undefined'
                    );
                }
            } else {
                /* $controller = new ErrorController(new Error(), new ErrorView, 
                  $result->returnCode, $result->message);
                  $controller->returnError(); */
                return array(
                    'tagid' => 'undefined',
                    'tagname' => 'undefined'
                );
            }
        } else {
            return array(
                'tagid' => 'undefined',
                'tagname' => 'undefined'
            );
        }
    }

    public static function createTag($tagName, $keywords, $groupId) {
        if (User::getCurrentUserId()) {
            $db = Database::getInstance();
            $tagId = $db->getID("tags", "tagid");
            $userId = User::getCurrentUserId();
            $keywords = rtrim($keywords, ',');
            $query = "INSERT INTO tags (tagid, tagname, keywords, userid, groupid) VALUES ('$tagId', '$tagName', '$keywords', 
                '$userId', '$groupId')";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                return json_encode(array(
                    'id' => $tagId,
                    'name' => $tagName,
                    'keywords' => $keywords,
                    'groupId' => $groupId
                ));
            } else {
                return "false";
            }
        } else {
            return "false";
        }
    }

    /**
     * 
     * @param type $_filter
     * @return type
     * get email and password from client by $_filter
     * then check data from db to set Session and return user's email 
     * or return false for log in
     */
    public static function getLogin($login) {
        $login = get_object_vars($login);
        $db = Database::getInstance();
        $email = $login["email"];
        $password = $login["password"];
        $query = "SELECT * FROM users WHERE email = '$email'";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $row = $result->dataTable->rows[0];
                //if($rows["password"] == md5($password)) {
                if ($row["password"] == $password) {
                    session_start();
                    global $userId;
                    $_SESSION['userid'] = $row["userid"];
                    $_SESSION['switchfrom'] = '';
                    $userId = $row["userid"];
                    session_write_close();
                    $query = "INSERT INTO user_logs (userid) VALUES ($userId)";
                    $db->query($query);
                    return (object) array(
                        'email' => $row["email"],
                        'password' => 'buzzpulse',
                        'name' => $row["fullname"],
                        'company' => $row["company"],
                        'address' => $row["address"],
                        'phone' => $row["phone"],
                        'position' => $row["position"],
                        'dateregistered' => $row["dateregistered"],
                        'token' => $row["token"],
                        'timezone' => $row["timezone"],
                    );
                } else {
                    return NULL;
                }
            } else {
                /* $controller = new ErrorController(new Error(), new ErrorView(), 
                  "404", "Not found any user with provided email");
                  $controller->returnError(); */
                return NULL;
            }
        } else {
            /* $controller = new ErrorController(new Error(), new ErrorView, 
              $result->returnCode, $result->message);
              $controller->returnError(); */
            return NULL;
        }
    }

    public static function getInfo() {
        if (User::getCurrentUserId()) {
            $db = Database::getInstance();
            $userId = User::getCurrentUserId();
            $query = "SELECT * FROM users WHERE userid = '$userId'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow == 1) {
                    $row = $result->dataTable->rows[0];
                    return array(
                        'email' => $row["email"],
                        'password' => 'buzzpulse',
                        'name' => $row["fullname"],
                        'company' => $row["company"],
                        'address' => $row["address"],
                        'phone' => $row["phone"],
                        'position' => $row["position"],
                        'dateregistered' => $row["dateregistered"],
                        'token' => $row["token"],
                        'timezone' => $row["timezone"]
                    );
                } else {
                    /* $controller = new ErrorController(new Error(), new ErrorView(), 
                      "404", "Not found any user with provided email"); */
                    return array(
                        'email' => 'undefined'
                    );
                }
            } else {
                /* $controller = new ErrorController(new Error(), new ErrorView, 
                  $result->returnCode, $result->message);
                  $controller->returnError(); */
                return array(
                    'email' => 'undefined'
                );
            }
        } else {
            return array(
                'email' => 'undefined'
            );
        }
    }

    public static function getTimeZone($name, $location) {
        $db = Database::getInstance();
        $query = "SELECT * FROM timezone WHERE fullname = '$name' AND location = '$location'";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $row = $result->dataTable->rows[0];
                return $row["timezone"];
            } else {
                /* $controller = new ErrorController(new Error(), new ErrorView(), 
                  "404", "Not found any user with provided email"); */
                return 00;
            }
        } else {
            /* $controller = new ErrorController(new Error(), new ErrorView, 
              $result->returnCode, $result->message);
              $controller->returnError(); */
            return 00;
        }
    }

    public static function getNameZone($timezone) {
        $db = Database::getInstance();
        $query = "SELECT * FROM timezone WHERE timezone = '$timezone'";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $row = $result->dataTable->rows[0];
                return $row["location"] + '/' + $row["fullname"];
            } else {
                /* $controller = new ErrorController(new Error(), new ErrorView(), 
                  "404", "Not found any user with provided email"); */
                return 'undefined';
            }
        } else {
            /* $controller = new ErrorController(new Error(), new ErrorView, 
              $result->returnCode, $result->message);
              $controller->returnError(); */
            return 'undefined';
        }
    }

    /**
     * 
     * @return User list
     */
    public static function listUser($allContact = false, $teamId = '') {
        $db = Database::getInstance();
        $user = User::withId(User::getCurrentUserId());
        $queryTeamId = $user->teamId;
        if ($teamId != '')
            $queryTeamId = $teamId;
        if (!$allContact)
            $query = "SELECT * FROM users WHERE teamid = '$queryTeamId'";
        else
            $query = "SELECT * FROM users";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow > 0) {
                $users = array();
                foreach ($result->dataTable->rows as $row) {
                    $user = new self();
                    $user->id = $row["userid"];
                    $user->name = $row["fullname"];
                    $user->password = $row["password"];
                    $user->email = $row["email"];
                    $user->phone = $row["phone"];
                    $user->address = $row["address"];
                    $user->company = $row["company"];
                    $user->position = $row["position"];
                    $user->dateRegistered = $row["dateregistered"];
                    $user->token = $row["token"];
                    $user->timezone = $row["timezone"];
                    $user->managerId = $row["managerid"];
                    $user->teamId = $row["teamid"];
                    $user->type = $row["type"];
                    $users[] = $user;
                }
                return $users;
            } else {
                $controller = new ErrorController(new Error(), new ErrorView(), "404", "Not found any user with provided email");
                $controller->returnError();
                return NULL;
            }
        } else {
            $controller = new ErrorController(new Error(), new ErrorView, $result->returnCode, $result->message);
            $controller->returnError();
            return NULL;
        }
    }

    /**
     * 
     * @param type $_filter
     * @return type
     * get register user of information from client by $_filter
     * then insert into database and return result user's email or false
     */
    public static function addUser($user) {
        if (User::getCurrentUserId()) {
            $db = Database::getInstance();
            $id = $db->getID("users", "userid");
            $name = $user["fullname"];
            $password = $user["password"];
            $email = $user["email"];
            $phone = $user["phone"];
            $address = $user["address"];
            $company = $user["company"];
            $position = $user["position"];
            $timezone = $user["timezone"];
            $dateRegistered = $user["dateregistered"];
            $token = $user["token"];
            $managerId = User::getCurrentUserId();
            $type = 3;
            $curUser = User::withId(User::getCurrentUserId());
            $teamId = $curUser->teamId;
            $query = "INSERT INTO users (userid, email, password, fullname, company, address, 
                phone, position, dateregistered, token, timezone, managerid, teamid, type) VALUES 
                ('$id', '$email', '$password', '$name', '$company', '$address', '$phone', 
                '$position', '$dateRegistered', '$token', '$timezone', '$managerId', '$teamId', $type)";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                return 'true';
            } else {
                /* $controller = new ErrorController(new Error(), new ErrorView, 
                  $result->returnCode, $result->message);
                  $controller->returnError(); */
                return 'false';
            }
        } else {
            return 'false';
        }
    }

    public static function addFolder($folderName, $parentId) {
        if (User::getCurrentUserId()) {
            $db = Database::getInstance();
            $folderId = $db->getID("folders", "folderid");
            $userId = User::getCurrentUserId();
            $folderType = 3;
            $parentId = $parentId;
            $query = "INSERT INTO folders (folderid, userid, foldername, 
                foldertype, parentid) VALUES ('$folderId', '$userId', 
                '$folderName', '$folderType', '$parentId')";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                return "true";
            } else {
                return "false";
            }
        } else {
            return "false";
        }
    }

    public static function deleteUser($userid) {
        if (User::getCurrentUserId()) {
            $db = Database::getInstance();
            $query = "DELETE FROM users WHERE userid = '$userid'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                return "true";
            } else {
                /* $controller = new ErrorController(new Error(), new ErrorView, 
                  $result->returnCode, $result->message);
                  $controller->returnError(); */
                return "false";
            }
        } else {
            return "false";
        }
    }

    public static function getLogedInUser() {
        $userId = $_SESSION["userid"];
        $user_ = self::withId($userId);
        if (self::getSwitchFrom() != '') {
            $user_->type = 1;
            $user_->managerId = 0;
            global $user;
            $user->type = 1;
            $user->managerId = 0;
        }
        return $user_;
    }

    public static function changePassword($oldPassword, $newPassword) {
        $userId = $_SESSION["userid"];
        $user = User::withId($userId);
        if ($user->password == $oldPassword) {
            $user->password = $newPassword;
            $userController = new UserController($user, new UserView());
            if ($userController->Save())
                return "succeed";
            else
                return "failed";
        }
        else {
            return "Wrong password!";
        }
    }

    public static function changeName($name) {
        $userId = $_SESSION["userid"];
        $user = User::withId($userId);
        $user->name = $name;
        $userController = new UserController($user, new UserView());
        if ($userController->Save())
            return "succeed";
        else
            return "failed";
    }

    public static function getAccounts() {
        if (User::getCurrentUserId()) {
            $db = Database::getInstance();
            $userId = User::getCurrentUserId();

            //getTwitters
            $query = "SELECT * FROM twitters WHERE userid = '$userId'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    foreach ($result->dataTable->rows as $row) {
                        $name = $row['screenname'];
                        $id = $row['twitterid'];
                        $userid = "$userid$id;";
                        $username = "$username$name;";
                    }
                }
            }
            $userid = $userid . 'twitter';
            $username = $username . 'twitter';

            //getFacebooks
            $query = "SELECT * FROM facebooks WHERE userid = '$userId'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    foreach ($result->dataTable->rows as $row) {
                        $name = $row['username'];
                        $id = $row['facebookid'];
                        $userid = "$userid$id;";
                        $username = "$username$name;";
                    }
                }
            }
            $userid = $userid . 'facebook';
            $username = $username . 'facebook';

            //getGoogles
            $query = "SELECT * FROM googles WHERE userid = '$userId'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    foreach ($result->dataTable->rows as $row) {
                        $name = $row['screenname'];
                        $id = $row['googleid'];
                        $userid = "$userid$id;";
                        $username = "$username$name;";
                    }
                }
            }
            $userid = $userid . 'google';
            $username = $username . 'google';

            //getLinkedIns
            $query = "SELECT * FROM linkedins WHERE userid = '$userId'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    foreach ($result->dataTable->rows as $row) {
                        $name = $row['screenname'];
                        $id = $row['linkedinid'];
                        $userid = "$userid$id;";
                        $username = "$username$name;";
                    }
                }
            }
            $userid = $userid . 'linkedin';
            $username = $username . 'linkedin';

            return array(
                "screenname" => $username,
                "accountid" => $userid
            );
        } else
            return array(
                "screenname" => 'undefined',
                "accountid" => 'undefined'
            );
    }

    public static function getCurrentUserId() {
        global $userId;
        return $userId;
    }

    public function getLastLogin() {
        $db = Database::getInstance();
        $query = "SELECT logindate FROM user_logs WHERE userid = $this->id ORDER BY logindate DESC";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow > 0) {
                $row = $result->dataTable->rows[0];
                $date = new DateTime($row['logindate']);
                return $date->format('F jS');
            } else {
                return "Unknown";
            }
        }
    }

    public static function getClientAccounts() {
        $db = Database::getInstance();
        $query = "SELECT * FROM users WHERE teamid != 2";
        $result = $db->query($query);
        $users = array();
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow > 0) {
                foreach ($result->dataTable->rows as $row) {
                    $user = new self();
                    $user->id = $row["userid"];
                    $user->name = $row["fullname"];
                    $user->password = $row["password"];
                    $user->email = $row["email"];
                    $user->phone = $row["phone"];
                    $user->address = $row["address"];
                    $user->company = $row["company"];
                    $user->position = $row["position"];
                    $user->dateRegistered = $row["dateregistered"];
                    $user->token = $row["token"];
                    $user->timezone = $row["timezone"];
                    $user->managerId = $row["managerid"];
                    $user->teamId = $row["teamid"];
                    $user->type = $row["type"];
                    $users[] = $user;
                }
            }
            return $users;
        }
        return NULL;
    }

    public static function getSwitchFrom() {
        global $userSwitchedFrom;
        return $userSwitchedFrom;
    }

}

?>
